package com.learn.concurrent.aqs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wangxing
 * @version 2020/8/19 22:25 Administrator
 */
public class LearnSemaphore {
    private static final Logger logger = LoggerFactory.getLogger(LearnSemaphore.class);
    static Semaphore s = new Semaphore(2);
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS,new ArrayBlockingQueue<>(10));
        for (int i = 0; i < 5; i++) {
            threadPoolExecutor.execute(()->{try {
                s.acquire();
                logger.info("thread name is {},acquire start time is :{}",Thread.currentThread().getName(), LocalDateTime.now().toString());
                TimeUnit.SECONDS.sleep(2);
                s.release();
                logger.info("thread name is {},acquire end time is :{}",Thread.currentThread().getName(),LocalDateTime.now().toString() );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }});
        }
        threadPoolExecutor.shutdown();
        logger.info("run end");
    }
}
